import axios from "axios";
import { Toast } from "zarm";
import { baseUrl } from "@/config.ts";
import { RegisterUser, LoginUser } from "@/page/Login/index.tsx";

const axiosInstance = axios.create({
  baseURL: baseUrl,
  timeout: 3000,
});

axiosInstance.interceptors.request.use(function (config) {
  config.headers["X-Requested-With"] = "XMLHttpRequest";
  config.headers["Content-Type"] = "application/json";
  const accessToken = localStorage.getItem("access_token");
  if (accessToken) {
    config.headers.authorization = `Bearer ${accessToken}`;
  }
  return config;
});
axiosInstance.interceptors.response.use(
  (res) => {
    return res;
  },
  (error) => {
    Toast.show(error.response.data.message || "网络错误");
  }
);
/**下面写接口函数以便于统一管理**/

// 注册页面获取验证码接口
export async function getCaptcha(username: string) {
  return await axiosInstance.get("/user/captcha", {
    params: {
      username,
    },
  });
}

// 注册页面的注册接口
export async function register(params: RegisterUser) {
  return await axiosInstance.post("/user/register", params);
}

export async function login(params: LoginUser) {
  return await axiosInstance.post("/user/login", params);
}
